const express = require('express');
const path = require('path');
const cors = require('cors');
const axios = require('axios');

const app = express();
app.use(cors());

const port = 3005;
const baseUrl = 'http://10.169.128.20/files/plugins';

console.log('插件服务器地址:', baseUrl);

// 获取插件列表
app.get('/pl', async (req: any, res: any) => {
  try {
    console.log('从服务器获取插件列表');
    const response = await axios.get(`${baseUrl}/plugins.json`);
    const plugins = response.data;

    // 确保每个插件都有完整的下载链接
    const processedPlugins = plugins.map((plugin: any) => ({
      ...plugin,
      downloadUrl: plugin.downloadUrl || `${baseUrl}/${plugin.id}.zip`
    }));

    res.setHeader('Content-Type', 'application/json');
    res.json(processedPlugins);
  } catch (error: any) {
    console.error('获取插件列表失败:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      headers: error.response?.headers
    });
    res.status(500).json({
      error: '获取插件列表失败',
      details: error.response?.data || error.message
    });
  }
});

// 下载插件
app.get('/download/:pluginId', async (req: any, res: any) => {
  const { pluginId } = req.params;
  const downloadUrl = `${baseUrl}/${pluginId}.zip`;

  try {
    console.log('尝试下载插件:', downloadUrl);
    const response = await axios({
      method: 'get',
      url: downloadUrl,
      responseType: 'stream'
    });

    console.log('插件下载成功，发送到客户端...');
    // 设置响应头
    res.setHeader('Content-Type', 'application/zip');
    res.setHeader('Content-Disposition', `attachment; filename=${pluginId}.zip`);

    // 将远程服务器的响应流传输到客户端
    response.data.pipe(res);
  } catch (error: any) {
    console.error('下载插件失败:', {
      pluginId,
      url: downloadUrl,
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    });
    res.status(500).json({
      error: '下载插件失败',
      details: error.response?.data || error.message
    });
  }
});

// 封装启动函数
export const startServer = async () => {
  return new Promise<void>((resolve, reject) => {
    app.listen(port, () => {
      // console.log(`Plugin market is running on http://localhost:${port}`);
      resolve();
    }).on('error', (err: any) => {
      reject(err);
    });
  });
};